/*
 * JMFViewRootComponent.java
 *
 * Created on June 3, 2007, 6:21 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package info.javatech.jmf.components.root.server;

import com.sun.faces.util.Util;
import info.javatech.jmf.common.ProtocolConstants;
import info.javatech.jmf.server.protocol.PResponse;
import info.javatech.jmf.server.protocol.PScreen;
import info.javatech.jmf.server.protocol.PScreenContainer;
import info.javatech.jmf.server.util.EncodeUtils;
import java.io.IOException;
import javax.faces.FacesException;
import javax.faces.application.StateManager;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.servlet.http.HttpSession;

/**
 *
 * @author afedotov
 */
public class RootComponent extends UIComponentBase {
    
    private PScreen pScreen;
    private PScreenContainer pScreenContainer;
    
    /** Creates a new instance of JMFViewRootComponent */
    public RootComponent() {
        setRendererType(null);
    }
    
    public String getFamily() {
        return "jmf.root";
    }
    
    public void encodeEnd(FacesContext context) throws IOException {
        
        StateManager stateManager = Util.getStateManager(FacesContext.getCurrentInstance());
        Object[] stateToWrite = (Object[])stateManager.saveView(FacesContext.getCurrentInstance());
        
        ResponseWriter wr = context.getResponseWriter();
        
        PResponse resp = new PResponse();
        
        if (stateToWrite[0]!=null)
            resp.setViewState((String) stateToWrite[0]);
        else if (stateToWrite[1]!=null)
            resp.setViewState((String) stateToWrite[1]);
        else throw new FacesException("stateToWrite content seems invalid");
        
        if (pScreen!=null) {
            resp.setViewType(ProtocolConstants.ROOT_COMPONENT_KIND_SCREEN);
            resp.setScreen(pScreen);
        } else if (pScreenContainer!=null) {
            resp.setViewType(ProtocolConstants.ROOT_COMPONENT_KIND_SCREEN_CONTAINER);
            resp.setScreenContainer(pScreenContainer);
        } else throw new FacesException("RootComponent should have at least one child of type FormComponent or DisplayableComponent");
        
        
        String actionURL = context.getApplication().getViewHandler().
                getActionURL(context, context.getViewRoot().getViewId());
        
        resp.setViewId(actionURL);
        resp.setSessionId(((HttpSession)context.getExternalContext().getSession(true)).getId());
        
        wr.startElement("root",this);
        wr.writeText(EncodeUtils.encodeToString(resp),"");
        wr.endElement("root");
    }
    
    public void setPScreen(PScreen pScreen) {
        this.pScreen = pScreen;
    }
    
    public void setPScreenContainer(PScreenContainer pScreenContainer) {
        this.pScreenContainer = pScreenContainer;
    }
    
    
}
